package com.example.crm.servlet;

import com.example.crm.pojo.Customer;
import com.example.crm.service.ICustomerService;
import com.example.crm.service.Impl.CustomerServiceImpl;
import org.apache.commons.beanutils.BeanUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@WebServlet("/customerServlet")
public class CustomerServlet extends BaseServlet{

    ICustomerService customerService = new CustomerServiceImpl();

    public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        // 查询客户信息 放入请求

        //
        req.getRequestDispatcher("jsp/customer/list.jsp").forward(req,resp);

    }
    public void addsubmit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        // 1.
        Customer c = new Customer();
        try {
            BeanUtils.populate(c,req.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        // 2.
        boolean result  = customerService.add(c);

        // 3.
//        resp.sendRedirect("jsp/customer/list.jsp");
        resp.sendRedirect("customerService?method=list");
    }

    public void editsubmit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        Customer c = new Customer();
        try {
            BeanUtils.populate(c,req.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        boolean result = customerService.update(c);

        resp.sendRedirect("customerServlet?method=list");
    }

    public void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        // 1. 接收编号
        String cust_id = req.getParameter("cust_id");
        long custId = Long.parseLong(cust_id);

        // 2. 查询用户
        Customer c = customerService.findById(custId);
        req.setAttribute("customer",c);

        // 3. 请求转发jsp
        req.getRequestDispatcher("jsp/customer/edit.jsp").forward(req,resp);

    }

    public void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        // 1. 接收要删除的编号
        String cust_id = req.getParameter("cust_id");
        long custId = Long.parseLong(cust_id);

        // 2. 执行删除
        customerService.delete(custId);


        // 3. 跳转到列表页
        resp.sendRedirect("customerServlet?method=list");

    }
}